﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JrGreenMonster
{

    public class TimeDelayItem : IComparable
    {
        public TimeDelayWatcher.TaskId Id { get; set; }
        public DateTime LastRun { get; set; }
        public int DelayMs { get; set; }

        #region IComparable Members

        public int CompareTo(object obj)
        {
            return DelayMs - ((TimeDelayItem)obj).DelayMs;
        }

        #endregion
    }

    /// <summary>
    /// Simple class to help wath delays between periodical jobs
    /// </summary>
    public class TimeDelayWatcher
    {

        protected TimeDelayItem[] m_arDelays = null;

        /// <summary>
        /// Available tasks to watch
        /// </summary>
        public enum TaskId { CstSignalUpload };

        /// <summary>
        /// Initializes all task delays
        /// </summary>
        public TimeDelayWatcher()
        {
            m_arDelays = new TimeDelayItem[1];
            m_arDelays[(int)TaskId.CstSignalUpload] = new TimeDelayItem() { Id = TaskId.CstSignalUpload, LastRun = DateTime.MinValue, DelayMs = 0 };
        }

        /// <summary>
        /// Sets new delay between runs (milliseconds)
        /// </summary>
        /// <param name="taskId">ID of task</param>
        /// <param name="delayMs">Delay in ms</param>
        public void SetDelayBetweenRunsMs(TaskId id, int delayMs)
        {
            m_arDelays[(int)id].DelayMs = delayMs;
        }

        /// <summary>
        /// Sets last run of task to now
        /// </summary>
        /// <param name="id"></param>
        public void Touch(TaskId id)
        {
            m_arDelays[(int)id].LastRun = DateTime.Now;
        }

        public int GetSecondsFromLastRun(TaskId id)
        {
            if(m_arDelays[(int)id].LastRun == DateTime.MinValue)
            {
                return int.MaxValue;
            }

            return (int)((TimeSpan)(DateTime.Now - m_arDelays[(int)id].LastRun)).TotalSeconds;
        }

        public int GetSecondsTillNextRun(TaskId id)
        {
            return m_arDelays[(int)id].DelayMs - GetSecondsFromLastRun(id);
        }

        /// <summary>
        /// Returns how many seconds before first of task should be run
        /// </summary>
        /// <returns></returns>
        public int GetSecondsTillFirstRun()
        {
            return m_arDelays.Min().DelayMs;
        }
    }
}
